package vip.bblog.oauth2.controller;

import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * @author <a href="1396513066@qq.com">Yu Yong</a>
 * @version 1.0
 * @date 2019年05月10日 8:54
 * @desc Oauth2Controller oauth认证
 */
@Controller
@RequestMapping("/oauth2")
@SessionAttributes("authorizationRequest")
public class Oauth2Controller {

    @GetMapping("/authorize")
    public String authorize(ModelAndView modelAndView) {
        return "/oauth2/login";
    }

    /**
     * 资源服务器请求用户信息接口
     *
     * @param principal
     * @return
     */
    @GetMapping("/check_user")
    @ResponseBody
    public Principal principal(Principal principal) {
        return principal;
    }

    @GetMapping("/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        if (request.getAttribute("_csrf") != null) {
            model.put("_csrf", request.getAttribute("_csrf"));
        }
        AuthorizationRequest authorizationRequest = (AuthorizationRequest) model.get("authorizationRequest");
        ModelAndView view = new ModelAndView();
        view.setViewName("/oauth2/grand");
        view.addObject("clientId", authorizationRequest.getClientId());
        return view;
    }
}
